import Model from "../utils/model";
import request from "../utils/request";
export default {
  data() {
    return {
      submiting: false,
      listLoading: false,
      list: null,
      params: {},

      isEditing: false,
      dialogFormVisible: false,
      UPLOAD_URL: '/util/upload'
    };
  },
  props: {
    filters: {
      type: Object,
      default: () => {
        return {}
      }
    }
    // ,

    // total:{
    //   type:Number,
    //   default:0
    // }
  },
  created() {
    this._temp = Object.assign({}, this.temp);
  },
  methods: {
    imgUrl(url) {
      if (!url) {
        return url;
      }
      if (url.indexOf('://') != -1) {
        return url;
      }
      if (url[0] != '/') {
        url = '/' + url;
      }
      if (url.indexOf('/images/') != -1 || url.indexOf('/imgs/') != -1) {
        return url;
      }
      if(url.indexOf('/oss-image/')!=-1){
        return 'http://weixin-ostorage01.oss-cn-shenzhen.aliyuncs.com'+url;
     }
      return 'https://weixina01.bppc.com.cn/zy-admin/UploadFiles/zy/product' + url;
    },
    goodsStatusData() {
      return ["出售中", "下架区", "仓库中"];
    },
    authStatus() {
      return ['待审核', '审核中', '审核通过', '审核不通过'];
    },
    handleAvatarSuccess(imgField) {
      return (res, file) => {
        console.log(file)
        if (res && res.errcode == 0) {
          this.temp[imgField] = res.info;
        }
      }
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleUpdate(row) {
      this.__onHandleUpdate && this.__onHandleUpdate(row)
      if (row) {
        Object.keys(this.temp).forEach(key => {
          if (key in row) {
            this.temp[key] = row[key];
          } else {
            if (Array.isArray(this.temp[key]) && this.temp[key].length == 0) {
              this.temp[key] = [];
            } else {
              this.temp[key] = '';
            }
          }
        });
        this.__onAfterHandleEditUpdate && this.__onAfterHandleEditUpdate(row)
        this.isEditing = true;
      } else {
        Object.keys(this._temp).forEach(key => {
          this.temp[key] = this._temp[key];
        });
        this.isEditing = false;
      }
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    init(modelname, mode) {
      this.$model = Model.create(modelname, mode);
      return this;
    },
    sortChange(e) {
      //  console.log(e);
      let sort = e.prop;
      let order = e.order;
      let orderType;
      if (order == "ascending") {
        orderType = "asc";
      } else if (order == "descending") {
        orderType = "desc";
      }
      if (sort && orderType) {
        this.params.order = sort;
        this.params.sort = orderType;
        this.loadData();
      } else {
        this.params.order = "";
        this.params.sort = "";
        this.loadData();
      }
    },
    _parseFilters() {
      for (let key in this.filters) {
        let value = this.filters[key];
        if (typeof value == 'string') {
          value = value.trim();
        }
        let kv = key.split("$");
        let op = "eq";
        if (kv.length == 2) {
          key = kv[1];
          op = kv[0];
        }
        if (value && this.__onParseFilterValue) {
          value = this.__onParseFilterValue(key, op, value)
        }
        this.$model.where({
          [key]: [op, value]
        });
      }
      return this;
    },
    getFilterRules(){
      return this.$model.filterBuilder.toString();
    },
    _parseParams() {
      this.$model.addParam(this.params);
      return this;
    },
    combOptions(modelname, filters) {
      return request({
        url: '/admin/query/options',
        method: 'get',
        params: {
          model: modelname,
          filterRules: JSON.stringify(filters) || ''
        }
      })
    },
    loadData() {
      this._parseFilters();
      this._parseParams();
      this.listLoading = true;
      this.$model
        .select()
        .then(info => {
          this.listLoading = false;
          this.list = info.rows;
          this.total = info.total;
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    handleSizeChange(size) {
      this.$model.addParam("limit", size);
      this.loadData();
    },
    addParam(key, value) {
      this.$model.addParam(key, value);
      return this;
    },
    $success(msg) {
      this.$message({
        type: "success",
        message: msg || "操作成功!"
      });
    },
    $warning(msg) {
      this.$message({
        type: "warning",
        message: msg
      });
    },
    $$notify(msg) {
      this.$notify({
        title: "成功",
        message: msg || "操作成功",
        type: "success",
        duration: 2000
      });
    },
    $error(msg) {
      this.$message({
        type: "error",
        message: msg
      });
    },
    $$comfirm(msg, sureCallback) {
      this.$confirm(msg, "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(sureCallback).catch(_ => {});
    },
    handleFilter() {
      this.$model.addParam("page", 1);
      this.loadData();
    },
    $query(method, data) {
      return this.$get(method, data)
    },
    $get(method, data) {
      return this.$get(method, data)
    },
    submitFormAction() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.__onFormSubmit) {
            if (this.__onFormSubmit() === false) {
              this.$nextTick(() => {
                this.$refs["dataForm"].clearValidate();
              });
              return;
            }
          }
          this.submiting = true;
          let func = null;
          if (this.isEditing) {
            func = this.$model.save;

          } else {
            func = this.$model.add;
          }

          func
            .call(this.$model, this.temp)
            .then(() => {
              this.submiting = false;
              this.dialogFormVisible = false;
              this.$notify({
                title: "成功",
                message: "操作成功",
                type: "success",
                duration: 2000
              });
              if (this.__onFormSubmited && this.__onFormSubmited() === false) {
                return;
              }
              this.loadData();
            })
            .catch((info) => {
              this.submiting = false;
              this.$message({
                type: "warning",
                message: info || "更新失败!"
              });
            });
        }
      });
    },
    handleDelete(row) {
      this.$confirm("确认要删除吗？", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$model
          .removeById(row.id)
          .then(res => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            if (this.__onRowRemoved && this.__onRowRemoved(row) === false) {
              return;
            }
            this.loadData();
          })
          .catch((info) => {
            // this.$message({
            //   type: "warning",
            //   message: info || "删除失败"
            // });
          });
      });
    },
    handleCurrentChange(val) {
      this.$model.addParam("page", val);
      this.loadData();
    },
    $get(url, params) {
      return request({
        url,
        method: 'GET',
        params
      })
    },
    $post(url, data) {
      return request({
        url,
        method: 'POST',
        data
      })
    },
    exportExcel(options) {
      return this.$model.addParam(options).query("/admin/query/exportExcel");
    },
    openWin(newUrl) {
      // newUrl = "http://localhost:9098/" + newUrl;
      console.log(newUrl);
      let iframe = document.createElement("iframe");
      iframe.style.display = "none";
      let form = document.createElement("form");
      form.action = newUrl;
      form.method = "get";
      form.target = "_self";
      iframe.appendChild(form);
      document.body.appendChild(iframe);
      form.submit();
      setTimeout(() => {
        iframe.parentElement.removeChild(iframe);
      }, 100);
    }
  }
};
